<template>
  <div class="score-container">
    <el-table :data="scoreList" style="width: 100%">
      <el-table-column prop="activityName" label="考试/测评">
        <template #default="{row}">
          <div class="activity-name">
            <el-tag :type="row.type | activityTypeFilter" size="mini">
              {{ row.type | activityTypeNameFilter }}
            </el-tag>
            <span>{{ row.activityName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="score" label="成绩" width="120">
        <template #default="{row}">
          <span v-if="row.status === 3">{{ row.score }} / {{ row.totalScore }}</span>
          <span v-else class="no-score">--</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{row}">
          <el-tag :type="row.status | statusTagTypeFilter">
            {{ row.status | activityStatusFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="submitTime" label="提交时间" width="180">
        <template #default="{row}">
          {{ row.submitTime | formatDateTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{row}">
          <el-button
            type="text"
            @click="handleViewDetail(row)"
            :disabled="row.status !== 3">
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 成绩详情对话框 -->
    <el-dialog
      :title="currentScore.activityName"
      :visible.sync="detailDialogVisible"
      width="80%"
      top="5vh"
      :close-on-click-modal="false"
      @opened="handleDialogOpened"
    >
      <div class="score-detail">
        <div class="score-summary">
          <div class="score-item">
            <div class="score-label">得分</div>
            <div class="score-value">{{ currentScore.score }} / {{ currentScore.totalScore }}</div>
          </div>
          <div class="score-item">
            <div class="score-label">正确率</div>
            <div class="score-value">{{ currentScore.correctRate }}%</div>
          </div>
          <div class="score-item">
            <div class="score-label">用时</div>
            <div class="score-value">{{ timeUsed }} 分钟</div>
          </div>
          <div class="score-item">
            <div class="score-label">提交时间</div>
            <div class="score-value">{{ currentScore.submitTime | formatDateTime }}</div>
          </div>
        </div>

        <el-tabs v-model="activeDetailTab">
          <el-tab-pane label="答题详情" name="answers">
            <div class="answer-detail">
              <div v-for="(question, index) in currentScore.questions" :key="question.id" class="question-item">
                <div class="question-header">
                  <span class="question-index">第{{ index + 1 }}题</span>
                  <span class="question-score">{{ question.score }}分</span>
                  <el-tag
                    size="mini"
                    :type="question.isCorrect ? 'success' : 'danger'">
                    {{ question.isCorrect ? '正确' : '错误' }}
                  </el-tag>
                  <el-button
                    v-if="!question.isCorrect && question.canAppeal"
                    type="text"
                    size="mini"
                    @click="showAppealDialog(question)"
                    class="appeal-btn">
                    申诉
                  </el-button>
                </div>
<!--                <div class="question-content" v-html="question.content"></div>-->
                <formula-renderer class="question-content" v-html="question.content" />


                <div v-if="question.options && question.options.length > 0" class="question-options">
                  <div
                    v-for="option in question.options"
                    :key="option.id"
                    class="option-item"
                    :class="{
                      'correct-option': option.isCorrect,
                      'selected-option': option.selected,
                      'wrong-selected': option.selected && !option.isCorrect
                    }">
                    <span class="option-code">{{ option.optionCode }}.</span>
<!--                    <span class="option-content" v-html="option.content"></span>-->
                    <formula-renderer class="option-content" v-html="option.content" />

                  </div>
                </div>

                <div v-if="question.answerContent" class="question-answer">
                  <div class="answer-label">你的答案:</div>
<!--                  <div class="answer-content" v-html="question.answerContent"></div>-->
                  <formula-renderer class="answer-content" v-html="question.answerContent" />

                </div>

                <div v-if="question.correctAnswer" class="question-correct-answer">
                  <div class="correct-answer-label">正确答案:</div>
<!--                  <div class="correct-answer-content" v-html="question.correctAnswer"></div>-->
                  <formula-renderer class="correct-answer-content" v-html="question.correctAnswer" />

                </div>

                <div v-if="question.analysis" class="question-analysis">
                  <div class="analysis-label">解析:</div>
<!--                  <div class="analysis-content" v-html="question.analysis"></div>-->
                  <formula-renderer class="analysis-content" v-html="question.analysis" />

                </div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="成绩统计" name="statistics" v-if="currentScore.statistics">
            <div class="statistics-container">
              <div class="statistics-row">
                <div class="statistics-item">
                  <div class="statistics-title">班级平均分</div>
                  <div class="statistics-value">{{ currentScore.statistics.avgScore }}</div>
                </div>
                <div class="statistics-item">
                  <div class="statistics-title">最高分</div>
                  <div class="statistics-value">{{ currentScore.statistics.highestScore }}</div>
                </div>
                <div class="statistics-item">
                  <div class="statistics-title">最低分</div>
                  <div class="statistics-value">{{ currentScore.statistics.lowestScore }}</div>
                </div>
              </div>
              <div class="statistics-row">
                <div class="statistics-item">
                  <div class="statistics-title">班级排名</div>
                  <div class="statistics-value">{{ currentScore.statistics.rank }} / {{ currentScore.statistics.total }}</div>
                </div>
                <div class="statistics-item">
                  <div class="statistics-title">通过率</div>
                  <div class="statistics-value">{{ currentScore.statistics.passRate }}%</div>
                </div>
                <div class="statistics-item">
                  <div class="statistics-title">你的正确率</div>
                  <div class="statistics-value">{{ currentScore.correctRate }}%</div>
                </div>
              </div>

              <!-- 新增的统计图表 -->
              <div class="analysis-charts">
                <div class="chart-row">
                  <div class="chart-item">
                    <h4>题型得分分布</h4>
                    <div v-if="currentScore.typeScores && currentScore.typeScores.length" ref="typeScoreChart" style="height: 300px;"></div>
                    <el-empty v-else description="暂无题型得分数据" />
                  </div>
                  <div class="chart-item">
                    <h4>难度得分分布</h4>
                    <div v-if="currentScore.difficultyScores && currentScore.difficultyScores.length" ref="difficultyScoreChart" style="height: 300px;"></div>
                    <el-empty v-else description="暂无难度得分数据" />
                  </div>
                </div>

                <div class="chart-row">
                  <div class="chart-item full-width">
                    <h4>知识点掌握情况</h4>
                    <div v-if="currentScore.knowledgeScores && currentScore.knowledgeScores.length" ref="knowledgeScoreChart" style="height: 400px;"></div>
                    <el-empty v-else description="暂无知识点数据" />
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 申诉对话框 -->
    <el-dialog
      title="提交申诉"
      :visible.sync="appealDialogVisible"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form :model="appealForm" label-width="80px">
        <el-form-item label="题目内容">
<!--          <div v-html="currentAppealQuestion.content" class="appeal-question-content"></div>-->
          <formula-renderer v-html="currentAppealQuestion.content" class="appeal-question-content" />
        </el-form-item>
        <el-form-item label="你的答案">
<!--          <div v-if="currentAppealQuestion.answerContent" v-html="currentAppealQuestion.answerContent" class="appeal-answer-content"></div>-->
          <formula-renderer v-if="currentAppealQuestion.answerContent" v-html="currentAppealQuestion.answerContent" class="appeal-answer-content" />
          <div v-else class="appeal-no-answer">未作答</div>
        </el-form-item>
        <el-form-item label="正确答案">
<!--          <div v-html="currentAppealQuestion.correctAnswer" class="appeal-correct-answer"></div>-->
          <formula-renderer v-html="currentAppealQuestion.correctAnswer" class="appeal-correct-answer" />
        </el-form-item>
        <el-form-item label="申诉内容" prop="content" required>
          <el-input
            v-model="appealForm.content"
            type="textarea"
            :rows="4"
            placeholder="请详细说明申诉理由"
            maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="appealDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAppeal" :loading="appealSubmitting">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getStudentScores, getScoreDetail, submitAppeal } from '@/api/exam/score'
import { parseTime } from "@/utils/quiz"
import * as echarts from 'echarts'
import FormulaRenderer from "@/components/FormulaRenderer/index.vue";

export default {
  name: 'StudentScoreTab',
  components: {FormulaRenderer},
  props: {
    groupId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupId: this.groupId
      },
      scoreList: [],
      total: 0,
      currentScore: {
        activityName: '',
        type: 1,
        score: 0,
        totalScore: 100,
        correctRate: 0,
        submitTime: null,
        questions: [],
        statistics: null,
        typeScores: [],
        difficultyScores: [],
        knowledgeScores: [],
        startTime: null,
      },
      detailDialogVisible: false,
      activeDetailTab: 'answers',
      appealDialogVisible: false,
      currentAppealQuestion: {
        id: null,
        content: '',
        answerContent: '',
        correctAnswer: ''
      },
      appealForm: {
        recordId: null,
        questionId: null,
        content: ''
      },
      appealSubmitting: false,
      // 图表实例
      typeScoreChart: null,
      difficultyScoreChart: null,
      knowledgeScoreChart: null,
      // 图表数据缓存
      chartDataReady: false
    }
  },
  computed: {
    // 计算考试用时（分钟）
    timeUsed() {
      if (!this.currentScore.startTime || !this.currentScore.submitTime) {
        return '--'
      }
      const start = new Date(this.currentScore.startTime).getTime()
      const end = new Date(this.currentScore.submitTime).getTime()
      const minutes = Math.floor((end - start) / (1000 * 60))
      return minutes > 0 ? minutes : '<1'
    }
  },
  watch: {
    // 监听详情对话框显示状态
    detailDialogVisible(val) {
      if (val) {
        this.$nextTick(() => {
          if (this.chartDataReady) {
            this.initCharts()
          }
        })
      } else {
        this.disposeCharts()
      }
    },
    // 监听当前活动标签页变化
    activeDetailTab(val) {
      if (val === 'statistics') {
        this.$nextTick(() => {
          if (this.chartDataReady) {
            this.initCharts()
          }
        })
      }
    }
  },
  created() {
    this.getList()
  },
  beforeDestroy() {
    // 销毁图表实例
    this.disposeCharts()
  },
  methods: {
    getList() {
      getStudentScores(this.queryParams).then(response => {
        this.scoreList = response.rows
        this.total = response.total
      }).catch(error => {
        console.error('获取成绩列表失败:', error)
        this.$message.error('获取成绩列表失败')
      })
    },
    handleViewDetail(row) {
      getScoreDetail(row.recordId).then(response => {
        this.currentScore = response.data
        this.chartDataReady = true
        this.detailDialogVisible = true
      }).catch(error => {
        console.error('获取成绩详情失败:', error)
        this.$message.error('获取成绩详情失败')
      })
    },
    // 对话框完全打开后的回调
    handleDialogOpened() {
      if (this.chartDataReady) {
        this.initCharts()
      }
    },
    // 初始化所有图表
    initCharts() {
      this.disposeCharts()
      this.$nextTick(() => {
        this.initTypeScoreChart()
        this.initDifficultyScoreChart()
        this.initKnowledgeScoreChart()
      })
    },
    showAppealDialog(question) {
      this.currentAppealQuestion = {
        id: question.id,
        content: question.content,
        answerContent: question.answerContent,
        correctAnswer: question.correctAnswer
      }
      this.appealForm = {
        recordId: this.currentScore.id,
        questionAnswerId: question.id,
        groupId: this.groupId,
        content: ''
      }
      this.appealDialogVisible = true
    },
    submitAppeal() {
      if (!this.appealForm.content.trim()) {
        this.$message.warning('请输入申诉内容')
        return
      }

      this.appealSubmitting = true
      submitAppeal(this.appealForm).then(() => {
        this.$message.success('申诉提交成功')
        this.appealDialogVisible = false
        // 更新题目状态，禁止重复申诉
        const question = this.currentScore.questions.find(q => q.id === this.appealForm.questionId)
        if (question) {
          question.canAppeal = false
        }
      }).catch(error => {
        console.error('提交申诉失败:', error)
        this.$message.error('提交申诉失败')
      }).finally(() => {
        this.appealSubmitting = false
      })
    },

    // 销毁所有图表实例
    disposeCharts() {
      if (this.typeScoreChart) {
        this.typeScoreChart.dispose()
        this.typeScoreChart = null
      }
      if (this.difficultyScoreChart) {
        this.difficultyScoreChart.dispose()
        this.difficultyScoreChart = null
      }
      if (this.knowledgeScoreChart) {
        this.knowledgeScoreChart.dispose()
        this.knowledgeScoreChart = null
      }
    },

    // 初始化题型得分分布图表
    initTypeScoreChart() {
      const chartDom = this.$refs.typeScoreChart
      if (!chartDom || !this.currentScore.typeScores || this.currentScore.typeScores.length === 0) return

      this.typeScoreChart = echarts.init(chartDom)
      const data = this.currentScore.typeScores.map(item => ({
        name: item.typeName,
        value: item.percentage,
        score: item.totalScore,
        maxScore: item.maxScore
      }))

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: params => {
            return `
              <strong>${params.name}</strong><br/>
              得分率: ${params.value.toFixed(2)}%<br/>
              得分: ${params.data.score.toFixed(2)} / ${params.data.maxScore.toFixed(2)}
            `
          }
        },
        legend: {
          top: 'bottom',
          data: data.map(item => item.name)
        },
        series: [
          {
            name: '题型得分率',
            type: 'pie',
            radius: [50, 120],
            center: ['50%', '50%'],
            roseType: 'area',
            itemStyle: {
              borderRadius: 8
            },
            label: {
              show: true,
              formatter: '{b}: {d}%'
            },
            emphasis: {
              label: {
                show: true
              }
            },
            data: data.map(item => ({
              ...item,
              itemStyle: {
                color: this.getRandomColor()
              }
            }))
          }
        ]
      }

      this.typeScoreChart.setOption(option)
      window.addEventListener('resize', this.handleTypeScoreChartResize)
    },

    handleTypeScoreChartResize() {
      if (this.typeScoreChart) {
        this.typeScoreChart.resize()
      }
    },

    // 初始化难度得分分布图表
    initDifficultyScoreChart() {
      const chartDom = this.$refs.difficultyScoreChart
      if (!chartDom || !this.currentScore.difficultyScores || this.currentScore.difficultyScores.length === 0) return

      this.difficultyScoreChart = echarts.init(chartDom)
      const difficultyOrder = ['容易', '偏易', '中等', '偏难', '困难']
      const data = difficultyOrder
        .map(difficulty => {
          const item = this.currentScore.difficultyScores.find(d => d.difficultyName === difficulty)
          return item ? {
            name: item.difficultyName,
            value: item.percentage,
            score: item.totalScore,
            maxScore: item.maxScore
          } : {
            name: difficulty,
            value: 0,
            score: 0,
            maxScore: 0
          }
        })

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: params => {
            return `
              <strong>${params.name}</strong><br/>
              得分率: ${params.value.toFixed(2)}%<br/>
              得分: ${params.data.score.toFixed(2)} / ${params.data.maxScore.toFixed(2)}
            `
          }
        },
        radar: {
          indicator: data.map(item => ({
            name: item.name,
            max: 100
          })),
          radius: '65%'
        },
        series: [{
          type: 'radar',
          data: [{
            value: data.map(item => item.value),
            name: '得分率',
            areaStyle: {
              opacity: 0.2
            },
            lineStyle: {
              width: 2
            }
          }]
        }]
      }

      this.difficultyScoreChart.setOption(option)
      window.addEventListener('resize', this.handleDifficultyScoreChartResize)
    },

    handleDifficultyScoreChartResize() {
      if (this.difficultyScoreChart) {
        this.difficultyScoreChart.resize()
      }
    },

    // 初始化知识点掌握情况图表
    initKnowledgeScoreChart() {
      const chartDom = this.$refs.knowledgeScoreChart
      if (!chartDom || !this.currentScore.knowledgeScores || this.currentScore.knowledgeScores.length === 0) return

      this.knowledgeScoreChart = echarts.init(chartDom)
      const sortedData = [...this.currentScore.knowledgeScores]
        .sort((a, b) => b.percentage - a.percentage)

      const data = sortedData.map(item => ({
        value: [0, item.knowledgeName, item.percentage],
        meta: {
          knowledgeName: item.knowledgeName,
          totalScore: item.totalScore,
          maxScore: item.maxScore,
          percentage: item.percentage
        },
        itemStyle: {
          color: this.getHeatmapColor(item.percentage)
        }
      }))

      const knowledgeNames = sortedData.map(item => item.knowledgeName)

      const option = {
        tooltip: {
          position: 'top',
          formatter: params => {
            const meta = params.data.meta
            return `
              <strong>${meta.knowledgeName}</strong><br/>
              得分率: ${meta.percentage.toFixed(2)}%<br/>
              得分: ${meta.totalScore.toFixed(2)} / ${meta.maxScore.toFixed(2)}
            `
          }
        },
        grid: {
          height: '80%',
          top: '10%',
          left: '3%',
          right: '4%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['掌握程度'],
          splitArea: {show: true}
        },
        yAxis: {
          type: 'category',
          data: knowledgeNames,
          splitArea: {show: true},
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        visualMap: {
          min: 0,
          max: 100,
          calculable: true,
          orient: 'horizontal',
          left: 'center',
          bottom: '0%',
          inRange: {
            color: ['#F56C6C', '#E6A23C', '#67C23A']
          }
        },
        series: [{
          name: '知识点掌握情况',
          type: 'heatmap',
          data: data,
          label: {
            show: true,
            formatter: params => {
              return params.value[2].toFixed(0) + '%'
            }
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }

      this.knowledgeScoreChart.setOption(option)
      window.addEventListener('resize', this.handleKnowledgeScoreChartResize)
    },

    handleKnowledgeScoreChartResize() {
      if (this.knowledgeScoreChart) {
        this.knowledgeScoreChart.resize()
      }
    },

    // 辅助方法
    getRandomColor() {
      const colors = [
        '#5470C6', '#91CC75', '#FAC858', '#EE6666',
        '#73C0DE', '#3BA272', '#FC8452', '#9A60B4'
      ]
      return colors[Math.floor(Math.random() * colors.length)]
    },

    getHeatmapColor(percentage) {
      if (percentage >= 80) return '#67C23A'
      if (percentage >= 60) return '#E6A23C'
      return '#F56C6C'
    }
  },
  filters: {
    activityTypeFilter(type) {
      const map = {1: 'danger', 2: 'warning', 3: 'success'}
      return map[type] || ''
    },
    activityTypeNameFilter(type) {
      const map = {1: '考试', 2: '测评', 3: '作业'}
      return map[type] || ''
    },
    activityStatusFilter(status) {
      const map = {
        1: '未开始',
        2: '进行中',
        3: '已结束'
      }
      return map[status] || ''
    },
    statusTagTypeFilter(status) {
      const map = {
        1: 'info',
        2: 'warning',
        3: 'success'
      }
      return map[status] || ''
    },
    formatDateTime(date) {
      if (!date) return '--'
      return parseTime(date, '{y}-{m}-{d} {h}:{i}')
    }
  }
}
</script>

<style scoped>
.score-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.activity-name {
  display: flex;
  align-items: center;
}

.activity-name .el-tag {
  margin-right: 10px;
}

.no-score {
  color: #909399;
}

/* 成绩详情样式 */
.score-detail {
  padding: 0 20px;
}

.score-summary {
  display: flex;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.score-item {
  flex: 1;
  text-align: center;
}

.score-label {
  color: #909399;
  font-size: 14px;
  margin-bottom: 5px;
}

.score-value {
  font-size: 24px;
  font-weight: bold;
}

/* 答题详情样式 */
.answer-detail {
  padding: 10px 0;
}

.question-item {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px dashed #ebeef5;
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.question-index {
  font-weight: bold;
  margin-right: 15px;
}

.question-score {
  color: #f56c6c;
  margin-right: 15px;
}

.appeal-btn {
  margin-left: auto;
}

.question-content {
  margin-bottom: 15px;
  line-height: 1.6;
}

.question-options {
  margin: 10px 0;
}

.option-item {
  padding: 8px 10px;
  margin-bottom: 5px;
  border-radius: 4px;
  background: #f5f7fa;
}

.correct-option {
  background: #f0f9eb;
  border-left: 3px solid #67c23a;
}

.selected-option {
  background: #ecf5ff;
  border-left: 3px solid #409eff;
}

.wrong-selected {
  background: #fef0f0;
  border-left: 3px solid #f56c6c;
}

.option-code {
  font-weight: bold;
  margin-right: 10px;
}

.question-answer,
.question-correct-answer,
.question-analysis {
  margin-top: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.answer-label,
.correct-answer-label,
.analysis-label {
  font-weight: bold;
  margin-bottom: 5px;
}

/* 统计信息样式 */
.statistics-container {
  padding: 20px 0;
}

.statistics-row {
  display: flex;
  margin-bottom: 20px;
}

.statistics-item {
  flex: 1;
  text-align: center;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  margin: 0 10px;
}

.statistics-title {
  color: #909399;
  font-size: 14px;
  margin-bottom: 5px;
}

.statistics-value {
  font-size: 20px;
  font-weight: bold;
}

/* 新增的分析图表样式 */
.analysis-charts {
  margin-top: 30px;
}

.chart-row {
  display: flex;
  margin-bottom: 20px;
}

.chart-item {
  flex: 1;
  padding: 15px;
  margin: 0 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.chart-item h4 {
  margin: 0 0 15px 0;
  text-align: center;
}

.full-width {
  flex: 0 0 100%;
  margin: 10px 0;
}

/* 申诉对话框样式 */
.appeal-question-content,
.appeal-answer-content,
.appeal-correct-answer {
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.appeal-no-answer {
  color: #909399;
  font-style: italic;
}
</style>
